package cn.xspace.module.other.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.JSONUtil;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.RequestConstant;
import com.xspace.android.xafcommon.util.ResourceUtils;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;
import com.xspace.android.xafcommon.view.dialog.ConfirmDialog;
import com.xspace.android.xafcommon.view.sdlv.DragListView;
import com.xspace.android.xafcommon.view.sdlv.Menu;
import com.xspace.android.xafcommon.view.sdlv.MenuItem;
import com.xspace.android.xafcommon.view.sdlv.SlideAndDragListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.bean.Type;
import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.module.other.R;
import cn.xspace.module.other.activity.share.WnxWebViewAct;
import cn.xspace.module.other.bean.FavoriteArticalBean;
import cn.xspace.module.other.bean.FavoriteFolderBean;
import cn.xspace.module.other.adapter.MyFavoriteAdapter;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MyFavoriteActivity extends BaseActivity implements SlideAndDragListView.OnListItemClickListener,
        SlideAndDragListView.OnMenuItemClickListener, DragListView.OnDragListener {

    public static final String TAG = MyFavoriteActivity.class.getSimpleName();

    private TitleBar mTitleBar;
    private LinearLayout mRlTitle;
    private ImageView mIvFavCenter;
    private SlideAndDragListView mListView;
    private Menu mMenu;
    private List<FavoriteArticalBean> mList;
    private List<FavoriteArticalBean> listTemp;
    private MyFavoriteAdapter myFavoriteAdapter;
    private String user_id;

    private List<FavoriteFolderBean> parentList = new ArrayList<>();
    private Map<String, List<FavoriteFolderBean>> childrenList = new HashMap<>();
    private PopupWindow popup;
    private ExpandAdpter expandAdapter;

    public static boolean isNeedRefresh = false;
    public static boolean isNeedReload = false;
    private String tempTitle;

    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedRefresh) {
            isNeedRefresh = false;
            queryAllFolder();
        }
        if (isNeedReload) {
            isNeedReload = false;
            popup = null;
            queryFavoriteWeb();
        }
    }

    @Override
    protected void getIntentData() {
        super.getIntentData();
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_my_favorite);
    }

    @Override
    protected void initFindViewById() {
        mTitleBar = (TitleBar) findViewById(R.id.fav_title_bar);
        mTitleBar.setTitleArrowVisibility(View.VISIBLE);
        mRlTitle = mTitleBar.getCenterLayout();
        tempTitle = getResources().getString(R.string.my_favorite_activity);
        mTitleBar.setTitle(tempTitle);
        mIvFavCenter = mTitleBar.getTitleArrow();
        mListView = (SlideAndDragListView) findViewById(R.id.slv_list);
        initMenu();
        mListView.setMenu(mMenu);
    }

    /**
     * 侧滑弹出的菜单内的条目
     */
    private void initMenu() {
        mMenu = new Menu(true, true);
        mMenu.addItem(new MenuItem.Builder().setWidth(ResourceUtils.getDimens(R.dimen.space_80))
                .setBackground(ResourceUtils.getDrawable(R.drawable.bg_menu_delete))
                .setDirection(MenuItem.DIRECTION_RIGHT)
//                .setText("删除")
                .setIcon(ResourceUtils.getDrawable(R.drawable.favorite_item_delete))
                .build());
        mMenu.addItem(new MenuItem.Builder().setWidth(ResourceUtils.getDimens(R.dimen.space_80))
                .setBackground(ResourceUtils.getDrawable(R.drawable.bg_menu_move))
                .setDirection(MenuItem.DIRECTION_RIGHT)
//                .setText("移动")
                .setIcon(ResourceUtils.getDrawable(R.drawable.favorite_item_move))
                .build());

    }

    @Override
    protected void initData() {
        user_id = MyInfoUtil.getMyUserid(this);
        mList = new ArrayList<>();
        listTemp = new ArrayList<>();
        myFavoriteAdapter = new MyFavoriteAdapter(this, listTemp);
        mListView.setAdapter(myFavoriteAdapter);
        mListView.setOnDragListener(this, listTemp);
        queryFavoriteWeb();
        queryAllFolder();
    }

    @Override
    protected void initEvent() {
        mListView.setOnListItemClickListener(this);
//        mListView.setOnSlideListener(this);
        mListView.setOnMenuItemClickListener(this);
        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, MyFavoriteManagerActivity.class);
                intent.putExtra("mode", 1);
                startActivity(intent);
            }
        });
        mRlTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initPop(v);
                setTextDropDown(true);
            }
        });
    }

    /**
     * 请求网络获取收藏数据,默认展示全部
     */
    private void queryFavoriteWeb() {
        showWaitDialog();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(RequestConstant.KEY_USER_ID, user_id);
        hashMap.put(RequestConstant.FOLDER_ID, null);
        OkHttpManager.getInstance().commonJsonPost(Constants.QueryFavoriteWeb, hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                        T.showShort(mContext, e.getMessage());
                    }

                    @Override
                    public void onNext(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String fileList = jsonObject.optString("fileList");
                            if (!TextUtils.isEmpty(fileList)) {
                                List<FavoriteArticalBean> list = JSONUtil.parseJsonToList(fileList, new
                                        TypeToken<List<FavoriteArticalBean>>() {
                                        }.getType());
                                mList.clear();
                                listTemp.clear();
                                mList.addAll(list);
                                listTemp.addAll(list);
                                LogUtil.d(TAG, "wubaojie>>>onNext: " + mList.toString());
                            } else {
                                mList.clear();
                                listTemp.clear();
                                T.showShort(mContext, "你还没有任何收藏");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        hideWaitDialog();
                        refreshList();
                    }
                });
    }

    private void queryAllFolder() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(RequestConstant.KEY_USER_ID, user_id);
        hashMap.put(RequestConstant.FOLDER_ID, null);
        OkHttpManager.getInstance().commonJsonPost(Constants.QueryFavoriteFolder, hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(String s) {
                        LogUtil.d(TAG, "wubaojie>>>onNext: " + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.optString("code");
//                            if ("0".equals(code)) {

                            JSONArray jsonArray = jsonObject.optJSONArray("folderList");
                            parseQueryAllFolder(jsonArray);
//                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 解析收藏夹的树结构
     *
     * @param jsonArray
     */
    private void parseQueryAllFolder(JSONArray jsonArray) {
        try {
            parentList.clear();
            childrenList.clear();
            parentList.add(new FavoriteFolderBean("我的收藏", "-1", "1"));
            if (jsonArray != null && jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject js = jsonArray.getJSONObject(i);
                    String folder_name = js.optString("folder_name");
                    String folder_id = js.optString("folder_id");
                    String isleaf = js.optString("isleaf");
                    if ("0".equals(isleaf)) {
                        JSONArray childListJS = js.optJSONArray("childList");
                        if (childListJS != null) {
                            List<FavoriteFolderBean> childlist_temp = new ArrayList<>();
                            for (int j = 0; j < childListJS.length(); j++) {
                                JSONObject jsj = childListJS.optJSONObject(j);
                                String folder_namej = jsj.optString("folder_name");
                                String folder_idj = jsj.optString("folder_id");
                                FavoriteFolderBean ffb_child = new FavoriteFolderBean(folder_namej, folder_idj, "0");
                                ffb_child.setParentId(folder_id);
                                childlist_temp.add(ffb_child);
                            }
                            childrenList.put(folder_id, childlist_temp);
                        }
                    }
                    FavoriteFolderBean ffb_temp = new FavoriteFolderBean(folder_name, folder_id, isleaf);
                    parentList.add(ffb_temp);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void refreshList() {
        myFavoriteAdapter.notifyDataSetChanged();
    }

    /**
     * 弹出popupWindow展示我的收藏页面
     *
     * @param v
     */
    private void initPop(View v) {

        if (popup == null) {
            View contentView = View.inflate(mContext, R.layout.myfavorite_web_list_pop, null);
            popup = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams
                    .WRAP_CONTENT, true);
            ExpandableListView expandView = (ExpandableListView) contentView.findViewById(R.id
                    .favorite_webs_list_expandlv);
            View touch = contentView.findViewById(R.id.favorite_webs_list_touch);
            touch.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismissPopUp();
                    setTextDropDown(false);
                }
            });
            expandAdapter = new ExpandAdpter(mContext, parentList, childrenList);
//            popup.setOutsideTouchable(true);
            popup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            expandView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
                @Override
                public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                    LogUtil.d(TAG, "wubaojie>>>onGroupClick: groupPos:" + groupPosition);
                    return false;
                }
            });
            expandView.setAdapter(expandAdapter);
        }
//        popup.setContentView(contentView);
//        popup.setWidth(StringToolkit.dip2px(mContext, 160));
//        int height = 250;
//        if (expandAdapter.getGroupCount() > 5) {
//            height = 350;
//        }
//        popup.setHeight(StringToolkit.dip2px(mContext, height));
        popup.showAsDropDown(mRlTitle);
//        popup.showAtLocation(v, Gravity.BOTTOM, 0, 0);
        mTitleBar.setTitle(getResources().getString(R.string.save_my_favorite));
        mTitleBar.setLeftLayoutVisibility(View.INVISIBLE);
        mTitleBar.setRightLayoutVisibility(View.INVISIBLE);
        popup.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                mTitleBar.setTitle(tempTitle);
                mTitleBar.setLeftLayoutVisibility(View.VISIBLE);
                mTitleBar.setRightLayoutVisibility(View.VISIBLE);
                setTextDropDown(false);
            }
        });
    }

    private void setTextDropDown(boolean isshow) {
        if (isshow) {
            mIvFavCenter.setImageResource(R.drawable.title_up);
        } else {
            mIvFavCenter.setImageResource(R.drawable.title_down);
        }
    }

    private void dismissPopUp() {
        if (popup != null)
            popup.dismiss();
    }

    @Override
    public void onListItemClick(View v, int position) {
        int index = position - mListView.getHeaderViewsCount();
        LogUtil.d(TAG, "wubaojie>>>onListItemClick: position :" + position + " index :" + index);
        FavoriteArticalBean bean = listTemp.get(index);
        Intent intent = new Intent(mContext, WnxWebViewAct.class);
//        intent.putExtra(Constants.TITITL, bean.file_title);
        intent.putExtra(Constants.WEBVIEURL, bean.file_url);
        if (Type.collectionFromType.FROM_NOTOCE.equals(bean.msg_org)) { //通知公告时传递类型,不显示其余的条目
            intent.putExtra("type", MsgType.NOTICE.toNumber());
        } else if (Type.collectionFromType.FROM_WNX.equals(bean.msg_org)) {
            intent.putExtra("type", MsgType.WNX_MSG.toNumber());
        }
        intent.putExtra(RequestConstant.KEY_ORG_ID, bean.msg_deptid);//再次进入webView界面时传递机构id,用于展示机构详情
        intent.putExtra(RequestConstant.KEY_DEP_ID, bean.msg_deptid);
        intent.putExtra("Collection", false);//是否显示收藏
        startActivity(intent);
    }

    @Override
    public int onMenuItemClick(View v, int itemPosition, int buttonPosition, int direction) {
        switch (direction) {
            case MenuItem.DIRECTION_LEFT:
                switch (buttonPosition) {
                    case 0:
                        return Menu.ITEM_NOTHING;
                    case 1:
                        return Menu.ITEM_SCROLL_BACK;
                }
                break;
            case MenuItem.DIRECTION_RIGHT:
                switch (buttonPosition) {
                    case 0:
                        showDeleteDialog(itemPosition);
                        return Menu.ITEM_SCROLL_BACK;
                    case 1:
                        // TODO 移动条目
                        FavoriteArticalBean bean = listTemp.get(itemPosition);
                        Intent intent = new Intent(mContext, MyFavoriteManagerActivity.class);
                        intent.putExtra("mode", 2);
                        intent.putExtra("file_id", bean.id);
                        intent.putExtra("folder_id", bean.folder_id);
                        startActivity(intent);
                        return Menu.ITEM_SCROLL_BACK;
                }
        }
        return Menu.ITEM_NOTHING;
    }

    private void showDeleteDialog(final int position) {
//        DialogHelp.getMessageDialog(mContext,
//                ResourceUtils.getString(R.string.delete_fav_art), "",
//                ResourceUtils.getString(R.string.think_again_and_again),
//                ResourceUtils.getString(R.string.button_ok), null,
//                new ButtonClickListener() {
//                    @Override
//                    public void buttonClick(View view) {
//                        deleteOneItem(position);
//                    }
//                })
//                .show();
        new ConfirmDialog.Builder(mContext)
                .setTitleMsg(ResourceUtils.getString(R.string.delete_fav_art))
                .setContentVisible(View.GONE)
                .setLeftText(ResourceUtils.getString(R.string.think_again_and_again))
                .setRightText(ResourceUtils.getString(R.string.button_ok))
                .setRightListener(new ButtonClickListener() {
                    @Override
                    public void buttonClick(View view) {
                        deleteOneItem(position);
                    }
                })
                .setListener()
                .show();
    }

    private void deleteOneItem(final int position) {
        showWaitDialog();
        final FavoriteArticalBean bean = listTemp.get(position);
        HashMap<String, Object> map = new HashMap<>();
        map.put(RequestConstant.KEY_USER_ID, user_id);
        map.put(RequestConstant.KEY_FAV_ID, bean.id);
        map.put(RequestConstant.FOLDER_ID, bean.folder_id);
        OkHttpManager.getInstance().commonJsonPost(Constants.CancelFavoritePage, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(String s) {
                        hideWaitDialog();
                        LogUtil.d(TAG, "wubaojie>>>onNext: " + s);
                        mList.remove(bean);
                        listTemp.remove(position);
                        refreshList();
                    }
                });
    }

    Handler hd = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    refreshList();
                    break;
                case 1:
                    Toast.makeText(mContext, "你还没有收藏文章", Toast.LENGTH_SHORT).show();
                    break;
                case 2:// 按文件夹筛选
                    try {
                        FavoriteFolderBean bean = (FavoriteFolderBean) msg.obj;
                        Set<String> seting = null;
                        if (msg.arg1 == 0) {// 父类文件夹筛选
                            seting = new HashSet<>();
                            List<FavoriteFolderBean> fflist = childrenList.get(bean.getFolderId());
                            seting.add(bean.getFolderId());
                            if (fflist != null && fflist.size() > 0) {
                                for (int i = 0; i < fflist.size(); i++) {
                                    seting.add(fflist.get(i).getFolderId());
                                }
                            }
                        }
                        setFolderData(seting, bean.getFolderId(), msg.arg1);
                        tempTitle = bean.getFolderName();
                        mTitleBar.setTitle(bean.getFolderName());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public void setFolderData(Set<String> setFoldId, String folderid, int tag) {
        if (TextUtils.isEmpty(folderid) || "-1".equals(folderid)) {
            listTemp.clear();
            listTemp.addAll(mList);
        } else {
            listTemp.clear();
            for (int i = 0; i < mList.size(); i++) {
                FavoriteArticalBean ffb = mList.get(i);
                if (tag == 0) {
                    if (setFoldId != null) {//父类文件夹筛选
                        if (setFoldId.contains(ffb.getFolder_id()))
                            listTemp.add(ffb);
                    }
                } else if (tag == 1) {
                    if (ffb.getFolder_id().equals(folderid)) {
                        listTemp.add(ffb);
                    }
                }
            }
        }
        refreshList();
    }

    /**
     * 筛选文件夹 Adapter
     *
     * @author Administrator
     */
    public class ExpandAdpter extends BaseExpandableListAdapter {
        Context context;
        private List<FavoriteFolderBean> parentlist;
        private Map<String, List<FavoriteFolderBean>> childrenlist;

        public ExpandAdpter(Context context,
                            List<FavoriteFolderBean> parentlist,
                            Map<String, List<FavoriteFolderBean>> childrenlist) {
            super();
            this.context = context;
            this.parentlist = parentlist;
            this.childrenlist = childrenlist;
        }

        @Override
        public Object getChild(int arg0, int arg1) {
            return childrenlist.get(getGroupIdStr(arg0)).get(arg1);
        }

        @Override
        public long getChildId(int arg0, int arg1) {
            return 0;
        }

        @Override
        public View getChildView(int arg0, int arg1, boolean arg2, View view,
                                 ViewGroup arg4) {
            final FavoriteFolderBean ffb = (FavoriteFolderBean) getChild(arg0, arg1);
            if (view == null) {
                view = LayoutInflater.from(mContext).inflate(R.layout.favorite_manager_item, null);
            }
            view.setBackgroundResource(R.drawable.bg_fav_child_item);
            ImageView img = (ImageView) view.findViewById(R.id.favorite_weblist_pop_item_img);
            View tab = view.findViewById(R.id.view_tab);
            ImageView right = (ImageView) view.findViewById(R.id.favorite_weblist_pop_item_right);
            img.setVisibility(View.GONE);
            tab.setVisibility(View.VISIBLE);
            TextView tv_title = (TextView) view.findViewById(R.id.favorite_weblist_pop_item_tv);
            tv_title.setText(ffb.getFolderName());
            right.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Message msg = hd.obtainMessage();
                    msg.what = 2;
                    msg.arg1 = 1;
                    msg.obj = ffb;
                    hd.sendMessage(msg);
                    dismissPopUp();
                }
            });
            return view;
        }

        @Override
        public int getChildrenCount(int arg0) {

            String key = getGroupIdStr(arg0);
            List<FavoriteFolderBean> tl = childrenlist.get(key);
            if (tl != null) {
                return tl.size();
            }
            return 0;
        }

        @Override
        public Object getGroup(int arg0) {
            return parentlist.get(arg0);
        }

        @Override
        public int getGroupCount() {
            return parentlist.size();
        }

        @Override
        public long getGroupId(int arg0) {
            return arg0;
        }

        public String getGroupIdStr(int arg0) {
            FavoriteFolderBean fwb = (FavoriteFolderBean) getGroup(arg0);
            return fwb.getFolderId();
        }

        @Override
        public View getGroupView(int position, boolean isExpand, View view, ViewGroup arg3) {
            final FavoriteFolderBean ffb = (FavoriteFolderBean) getGroup(position);
            if (view == null) {
                view = View.inflate(mContext, R.layout.myfavorite_web_list_pop_item, null);
            }
            ImageView img = (ImageView) view.findViewById(R.id.favorite_weblist_pop_item_img);
            ImageView right = (ImageView) view.findViewById(R.id.favorite_weblist_pop_item_right);
            TextView tv_title = (TextView) view.findViewById(R.id.favorite_weblist_pop_item_tv);
            tv_title.setText(ffb.getFolderName());

//            if (getChildrenCount(position) > 0) {
            if (!isExpand) {
                img.setImageResource(R.drawable.green_triangle_right);
            } else {
                img.setImageResource(R.drawable.green_triangle_down);
            }
//            } else {
//                img.setImageResource(R.drawable.favorite_web_pop_item_ico);
//            }
            right.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Message msg = hd.obtainMessage();
                    msg.what = 2;
                    msg.arg1 = 0;
                    msg.obj = ffb;
                    hd.sendMessage(msg);
                    dismissPopUp();
                }
            });
            img.setVisibility((position == 0 ? View.INVISIBLE : View.VISIBLE));
            return view;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int arg0, int arg1) {
            return false;
        }

    }

    @Override
    public void onDragViewStart(int position) {

    }

    @Override
    public void onDragViewMoving(int position) {

    }

    @Override
    public void onDragViewDown(int position) {

    }
}
